<template>
  <div>
    <div>
      <div class="crumbs">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item>
            <i class="el-icon-lx-cascades"></i>
            血糖信息
          </el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="container">
        <div class="handle-box">
          <!-- <el-input
            v-model="query.userId"
            placeholder="用户ID"
            class="handle-input mr10"
          ></el-input> -->
          <el-input
            v-model="query.username"
            placeholder="用户姓名"
            class="handle-input mr10"
          ></el-input>
          <el-select
            v-model="query.dietStatus"
            placeholder="血糖测量状态"
            class="handle-select mr10"
          >
            <el-option
              v-for="item in options"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <el-button type="primary" @click="handleSearch"
            ><el-icon style="margin-right: 5px"><Search /></el-icon
            >搜索</el-button
          >
          <el-button type="primary" @click="resetSearch">清空</el-button>
          <el-button type="primary" @click="handleExportData"
            ><el-icon style="margin-right: 5px"><Download /></el-icon
            >导出血糖信息</el-button
          >
          <el-popconfirm
            title="确定要删除选中血糖信息？"
            confirm-button-text="确定"
            cancel-button-text="取消"
            @confirm="deleteAll"
          >
            <template #reference>
              <el-button type="danger">删除选中</el-button>
            </template>
          </el-popconfirm>
          <el-button type="primary" @click="show">展示折线图</el-button>
        </div>
        <el-table
          :data="tableData"
          border
          class="table"
          ref="multipleTable"
          header-cell-class-name="table-header"
          @selection-change="handleSelect"
          v-loading="loading"
        >
          <el-table-column type="selection" width="70" align="center" />
          <el-table-column label="序号" width="70" align="center">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>

          <el-table-column
            prop="user.username"
            label="用户姓名"
            width="150"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="user.realname"
            label="真实姓名"
            width="150"
            align="center"
          >
          </el-table-column>
          <el-table-column label="血糖测量状态" width="120" align="center">
            <template #default="scope">
              <el-tag
                :type="
                  scope.row.dietStatus == '0'
                    ? 'danger'
                    : scope.row.dietStatus == '1'
                    ? 'success'
                    : scope.row.dietStatus == '2'
                    ? 'success'
                    : scope.row.dietStatus == '3'
                    ? 'success'
                    : scope.row.dietStatus == '4'
                    ? 'success'
                    : scope.row.dietStatus == '5'
                    ? 'success'
                    : scope.row.dietStatus == '6'
                    ? 'success'
                    : scope.row.dietStatus == '7'
                    ? 'success'
                    : 'warning'
                "
              >
                {{
                  scope.row.dietStatus == '0'
                    ? '早餐前'
                    : scope.row.dietStatus == '1'
                    ? '早餐后'
                    : scope.row.dietStatus == '2'
                    ? '午餐前'
                    : scope.row.dietStatus == '3'
                    ? '午餐后'
                    : scope.row.dietStatus == '4'
                    ? '晚餐前'
                    : scope.row.dietStatus == '5'
                    ? '晚餐后'
                    : scope.row.dietStatus == '6'
                    ? '睡前'
                    : scope.row.dietStatus == '7'
                    ? '凌晨'
                    : '随机'
                }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="bloodglucoseValue"
            label="末梢血糖/动态血糖值"
            width="100"
            align="center"
          ></el-table-column>
          <el-table-column
            label="测量时间"
            class="content"
            align="center"
            prop="recordTime"
          >
          </el-table-column>
          <el-table-column
            prop="createdAt"
            label="创建时间"
            align="center"
          ></el-table-column>
          <el-table-column label="操作" width="180" align="center">
            <template #default="scope">
              <el-popconfirm
                title="确定要删除血糖信息？"
                confirm-button-text="确定"
                cancel-button-text="取消"
                @confirm="handleDelete(scope.$index, scope.row)"
              >
                <template #reference>
                  <el-button size="small" type="danger"
                    ><el-icon style="margin-right: 5px"><Delete /></el-icon
                    >删除</el-button
                  >
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            background
            layout="total, prev, pager, next"
            :current-page="query.pageIndex"
            :page-size="query.pageSize"
            :total="pageTotal"
            @current-change="handlePageChange"
          ></el-pagination>
        </div>
      </div>
    </div>
    <!-- 折线图 -->
    <div class="chartLineShow" v-if="chartLineShow">
      <div class="containertwo">
        <el-input
          v-model="query.chartLineBoxUserName"
          placeholder="用户姓名"
          class="handle-input mr10"
        ></el-input>
        <div>
          <el-date-picker
            v-model="query.chartLineBoxDate"
            type="daterange"
            unlink-panels
            range-separator="-"
            start-placeholder="起始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </div>

        <el-button
          type="primary"
          @click="handleSearchLineChart"
          style="margin-left: 10px"
          ><el-icon style="margin-right: 5px"><Search /></el-icon
          >搜索</el-button
        >
        <el-button type="primary" @click="chartLineShow = false"
          >关闭折线图</el-button
        >
      </div>
      <div
        id="chartLineBox"
        style="
          width: 100%;
          height: 70vh;
          background-color: white;
          margin-top: 10px;
        "
      ></div>
    </div>
  </div>
</template>
<script>
import { ref, reactive, onMounted, onBeforeMount } from 'vue'
import { ElMessageBox } from 'element-plus'
import request from '../../utils/request'
import { ElNotification } from 'element-plus'
import { ElMessage } from 'element-plus'
import XLSX from 'xlsx'
import router from '../../router'
// import { useRouter } from 'vue-router'
import * as echarts from 'echarts'
import { async } from '@kangc/v-md-editor'
import qs from 'qs'
export default {
  setup() {
    const loading = ref(true)
    const value1 = ref([])
    // const useRouter = useRouter()
    const tableData = ref([])
    const pageTotal = ref(0)
    const dialogVisible = ref(false)
    const form = reactive({
      content: '',
    })

    const options = [
      {
        value: '0',
        label: '早餐前',
      },
      {
        value: '1',
        label: '早餐后',
      },
      {
        value: '2',
        label: '午餐前',
      },
      {
        value: '3',
        label: '午餐后',
      },
      {
        value: '4',
        label: '晚餐前',
      },
      {
        value: '5',
        label: '晚餐后',
      },
      {
        value: '6',
        label: '睡前',
      },
      {
        value: '7',
        label: '凌晨',
      },
      {
        value: '8',
        label: '随机',
      },
    ]

    const query = reactive({
      userId: '',
      username: '',
      dietStatus: '',
      pageIndex: 1,
      pageSize: 6,
      chartLineBoxUserName: '',
      chartLineBoxDate: [],
      chartLineBoxUserId: '',
    })
    const ruleFormRef = ref()
    const ruleForm = ref({})

    // 查询操作
    const handleSearch = () => {
      getData()
    }

    // 重置
    const resetSearch = () => {
      query.userId = ''
      query.username = ''
      query.dietStatus = ''
      getData()
    }
    // 分页导航
    const handlePageChange = (val) => {
      loading.value = true
      query.pageIndex = val
      getData()
    }

    // 删除操作
    const handleDelete = (index, row) => {
      loading.value = true
      request
        .request({
          url: '/bloodglucose/deleteBloodglucose',
          method: 'get',
          params: {
            bloodglucoseIds: row.bloodglucoseId,
          },
        })
        .then((res) => {
          if (res.data.message == 'success') {
            getData()
            loading.value = false
            ElNotification({
              title: '删除成功',
              message: '成功删除用户信息',
            })
          } else {
            ElNotification({
              title: '删除失败',
              message: '请联系管理员检查失败原因',
            })
          }
        })
        .catch((e) => {
          ElNotification({
            title: '删除失败',
            message: '请联系管理员检查失败原因',
          })
        })
    }
    const chartLineX = ref([])
    const chartLineY = ref([])
    const chartLineShow = ref(false)
    // 获取表格数据
    const getData = () => {
      request
        .request({
          url: '/bloodglucose/getBloodglucoseByPageAndCondition',
          params: {
            userId: query.userId,
            username: query.username,
            dietStatus: query.dietStatus,
            currentPage: query.pageIndex,
            pageSize: query.pageSize,
          },
          method: 'get',
        })
        .then((res) => {
          tableData.value = res.data.data.rows
          pageTotal.value = res.data.data.count
          loading.value = false
        })
        .catch((e) => {
          console.log(e)
        })
    }

    getData()

    const selectArray = ref('')
    const handleSelect = (val) => {
      selectArray.value = []
      for (const iterator of val) {
        selectArray.value.push(iterator.bloodglucoseId)
      }
    }

    //删除全部选中
    const deleteAll = () => {
      loading.value = true
      JSON.stringify(selectArray.value)
      request
        .request({
          url: '/bloodglucose/deleteBloodglucose',
          method: 'get',

          params: {
            bloodglucoseIds: selectArray.value,
          },
          paramsSerializer: (params) => {
            return qs.stringify(params, { indices: false })
          },
        })
        .then((res) => {
          if (res.data.message == 'success') {
            getData()
            loading.value = false
            ElNotification({
              title: '删除成功',
              message: '成功删除血糖信息',
            })
          } else {
            ElNotification({
              title: '删除失败',
              message: '请联系管理员检查失败原因',
            })
          }
        })
        .catch((e) => {
          console.log(e)
          ElNotification({
            title: '删除失败',
            message: '请联系管理员检查失败原因',
          })
        })
    }
    /*
    * @description:
    * @param {Object} json 服务端发过来的数据
    * @param {String} name 导出Excel文件名字
   
    * @param {String} titleArr 导出Excel表头
   
    * @param {String} sheetName 导出sheetName名字
    * @return:
    */
    const exportData = ref([])
    const titleArr = [
      '记录时间',
      '创建时间',
      '更新时间',
      '血糖值',
      '血糖测量状态(0早餐前 1 早餐后 2午餐前 3午餐后 4晚餐前 5晚餐后 6睡前 7凌晨 8随机)',
      '用户ID',
      '真实姓名',
      '用户名',
    ] //表头中文名
    // 获取导出表格数据
    const handleExportData = () => {
      request
        .request({
          url: '/bloodglucose/getBloodglucoseByPageAndCondition',
          params: {
            currentPage: 1,
            pageSize: pageTotal.value,
          },
          method: 'get',
        })
        .then((res) => {
          //获取当前页的数据
          exportData.value = res.data.data.rows
          exportExcel(exportData.value, '血糖信息', titleArr, 'sheetName')
        })
        .catch((e) => {
          console.log(e)
        })
        .finally()
    }
    // 导出函数
    const exportExcel = (json, name, titleArr, sheetName) => {
      /* convert state to workbook */
      var data = new Array()
      var keyArray = new Array()
      const getLength = function (obj) {
        var count = 0
        for (var i in obj) {
          if (obj.hasOwnProperty.call(i)) {
            count++
          }
        }
        return count
      }

      for (const key1 in json) {
        if (Object.prototype.hasOwnProperty.call(json, key1)) {
          const element = json[key1]
          var rowDataArray = new Array()
          for (const key2 in element) {
            if (key2 == 'bloodglucoseId') {
              continue
            }
            if (Object.hasOwnProperty.call(element, key2)) {
              var element2 = ''
              var element3 = ''
              if (key2 == 'user') {
                element2 = element[key2].username
                element3 = element[key2].realname
                rowDataArray.push(element3)
              } else if (key2 == 'dietStatus') {
                if (element[key2] == 0) {
                  element2 = '早餐前'
                } else if (element[key2] == 1) {
                  element2 = '早餐后'
                } else if (element[key2] == 2) {
                  element2 = '午餐前'
                } else if (element[key2] == 3) {
                  element2 = '午餐后'
                } else if (element[key2] == 4) {
                  element2 = '晚餐前'
                } else if (element[key2] == 5) {
                  element2 = '晚餐后'
                } else if (element[key2] == 6) {
                  element2 = '睡前'
                } else if (element[key2] == 7) {
                  element2 = '凌晨'
                } else {
                  element2 = '随机'
                }
              } else {
                element2 = element[key2]
              }
              rowDataArray.push(element2)
              if (keyArray.length < getLength(element)) {
                keyArray.push(key2)
              }
            }
          }
          data.push(rowDataArray)
        }
      }
      // keyArray为英文字段表头
      data.splice(0, 0, keyArray, titleArr)
      const ws = XLSX.utils.aoa_to_sheet(data)
      const wb = XLSX.utils.book_new()
      // 此处隐藏英文字段表头
      var wsrows = [{ hidden: true }]
      ws['!rows'] = wsrows // ws - worksheet
      XLSX.utils.book_append_sheet(wb, ws, sheetName)
      /* generate file and send to client */
      XLSX.writeFile(wb, name + '.xlsx')
    }

    const getUsernameId = async () => {
      return await request
        .request({
          url: '/user/getUserByName',
          params: {
            username: query.chartLineBoxUserName,
          },
          method: 'get',
        })
        .then((res) => {
          return res.data.data
        })
        .catch((e) => {
          console.log(e)
        })
    }
    // 获取血糖信息
    const bloodglucose = (id) => {
      return request
        .request({
          url: '/bloodglucose/getBloodglucoseByDates',
          params: {
            userId: id,
            startDate: query.chartLineBoxDate[0],
            endDate: query.chartLineBoxDate[1],
          },
          method: 'get',
        })
        .then((res) => {
          return res.data.data
        })
        .catch((e) => {
          console.log(e)
        })
    }
    // 折线图
    const lineChart = async (value) => {
      const max = ref(10)
      chartLineX.value = []
      chartLineY.value = []
      if (value.length !== 0) {
        for (let item of value) {
          const status =
            item.dietStatus == '0'
              ? '早餐前'
              : item.dietStatus == '1'
              ? '早餐后'
              : item.dietStatus == '2'
              ? '午餐前'
              : item.dietStatus == '3'
              ? '午餐后'
              : item.dietStatus == '4'
              ? '晚餐前'
              : item.dietStatus == '5'
              ? '晚餐后'
              : item.dietStatus == '6'
              ? '睡前'
              : item.dietStatus == '7'
              ? '凌晨'
              : '随机'
          chartLineX.value.push(item.recordTime)
          chartLineY.value.push({
            name: status,
            value: item.bloodglucoseValue,
          })
          if (max.value < item.bloodglucoseValue) {
            max.value = item.bloodglucoseValue
          }
        }
      }

      var chartLine = echarts.init(document.getElementById('chartLineBox'))
      // 指定图表的配置项和数据
      var option = {
        tooltip: {
          //设置tip提示
          trigger: 'axis',
          axisPointer: {
            type: 'line',
          },
          formatter: function (params) {
            return (
              params[0].axisValue +
              '<br>血糖测量状态' +
              '<span style="float:right;">' +
              params[0].name +
              '</span>' +
              '<br>' +
              params[0].marker +
              '血糖值' +
              '<span style="font-weight: bolder;float:right;">' +
              params[0].value +
              '</span>'
            )
          },
        },

        legend: {
          //设置区分（哪条线属于什么）
          data: ['血糖值'],
        },
        color: ['#8AE09F'], //设置区分（每条线是什么颜色，和 legend 一一对应）
        xAxis: {
          //设置x轴
          type: 'category',
          boundaryGap: false, //坐标轴两边不留白
          data: chartLineX.value,
          name: '时间', //X轴 name
          nameTextStyle: {
            //坐标轴名称的文字样式
            color: '#FA6F53',
            fontSize: 16,
            padding: [0, 0, 0, 20],
          },
          axisLine: {
            //坐标轴轴线相关设置。
            lineStyle: {
              color: '#FA6F53',
            },
          },
        },
        yAxis: {
          name: '血糖值',
          nameTextStyle: {
            color: '#FA6F53',
            fontSize: 16,
            padding: [0, 0, 10, 0],
          },
          axisLine: {
            lineStyle: {
              color: '#FA6F53',
            },
          },
          type: 'value',
          min: 0,
          max: max.value,
        },
        series: [
          {
            name: '血糖值',
            data: chartLineY.value,
            type: 'line', // 类型为折线图
            lineStyle: {
              // 线条样式 => 必须使用normal属性
              normal: {
                color: '#8AE09F',
              },
            },
          },
        ],
        dataZoom: [
          //滑动条
          {
            xAxisIndex: 0, //这里是从X轴的0刻度开始
            show: false, //是否显示滑动条，不影响使用
            type: 'inside',
            startValue: 0, // 从头开始。
            endValue: 6, // 一次性展示6个。
          },
        ],
        title: {
          show: chartLineY.value.length == 0,
          text: '暂无数据',
          x: 'center',
          y: 'center',
          textStyle: {
            fontSize: 24,
            fontWeight: 'normal',
          },
        },
      }

      // 使用刚指定的配置项和数据显示图表。
      chartLine.setOption(option)
    }
    // 按测量时间排序
    const sort = (recordTime) => {
      return function (a, b) {
        let v1 = new Date(Date.parse(a[recordTime].replace(/-/g, '/')))
        let v2 = new Date(Date.parse(b[recordTime].replace(/-/g, '/')))
        return v1 - v2
      }
    }
    const handleSearchLineChart = async () => {
      if (query.chartLineBoxUserName == '') {
        ElMessage({
          message: '请输入用户名',
          type: 'error',
        })
        return
      } else if (
        query.chartLineBoxDate == '' ||
        query.chartLineBoxDate == null
      ) {
        ElMessage({
          message: '请选择日期',
          type: 'error',
        })
        return
      }
      const res = await getUsernameId()
      if (res.code == 500) {
        ElMessage({
          message: '用户不存在',
          type: 'error',
        })
        return
      }
      const res2 = await bloodglucose(res.userId)
      res2.sort(sort('recordTime'))
      lineChart(res2)
    }

    const show = () => {
      chartLineShow.value = true
      setTimeout(() => {
        lineChart([])
      }, 1)
    }

    // onBeforeMount(getData)
    return {
      loading,
      query,
      pageTotal,
      tableData,
      dialogVisible,
      form,
      ruleForm,
      ruleFormRef,
      options,
      value1,
      chartLineShow,

      getData,
      handleSearch,
      handlePageChange,
      handleDelete,
      handleSelect,
      resetSearch,
      exportExcel,
      handleExportData,
      lineChart,
      exportData,
      titleArr,
      deleteAll,
      handleSearchLineChart,
      show,
    }
  },
}
</script>
<style lang="scss" scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 150px;
}

.handle-input {
  width: 200px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}

.content {
  color: rgb(32, 27, 27);
  font-size: 35rpx;
  text-overflow: ellipsis;
  z-index: -1;
  display: -webkit-box;
  word-break: break-all;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 4;
  overflow: hidden;
}

.chartLineShow {
  margin-top: 40px;
}
.containertwo {
  display: flex;
  align-items: center;
}
</style>

<style>
.el-upload--text {
  height: auto;
  width: auto;
}
.mavonEditor {
  width: 100%;
  height: 100%;
}
</style>
